<?php

namespace app\common\controller;

use app\BaseController;
use app\model\AuthRuleTypeModel;
use app\model\CompanyConfigModel;
use app\model\ConfigModel;
use app\model\MessageModel;
use app\model\platform\PlatformConfigModel;
use app\model\UserModel;
use think\App;

class Index extends BaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 获取单位配置
     */
    public function getUnitConfig(): bool|string
    {
        try {
            $ConfigModel = new ConfigModel();
            $config = $ConfigModel->field('key,value')->where('unit_id','=',$this->userData['unit_id'])->select()->toArray();
            $configData = [];
            foreach ($config as $v){
                $configData[$v['key']] = json_decode($v['value'],true);
            }
            return success($configData);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 获取系统时间
     */
    public function getSystemTime(): bool|string
    {
        return success([
            'time' => time()
        ]);
    }

    /**
     * 权限规则类型
     * @return bool|string
     */
    public function typeList(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            $where[] = ['status', '=', 1];
            $AuthRuleTypeModel = new AuthRuleTypeModel();
            if (!empty($param['rule'])) {
                $id = explode(',', $param['rule']);
            } else {
                $id = [-1];
            }
            $data = $AuthRuleTypeModel->field('id,name,img,sort')->where($where)->with([
                'AuthRule' => function ($query) use ($id) {
                    $query->where('id', 'in', $id)->field('id,name,type_id,icon_shortcut');
                }
            ])->order('sort asc')->select()->toArray();
            $list = [];
            foreach ($data as $item) {
                if (!empty($item['AuthRule'])) {
                    $list[] = $item;
                }
            }
            return success($list);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 权限规则类型-区域版
     * @return bool|string
     */
    public function platformTypeList(): bool|string
    {
        try {
            $AuthRuleTypeModel = new AuthRuleTypeModel();
            $data = $AuthRuleTypeModel->field('id,name,img,sort')->where('status', '=', 1)->with([
                'PlatformAuthRule' => function ($query) {
                    $query->field('id,name,type_id,icon_shortcut');
                }
            ])->order('sort asc')->select()->toArray();
            $list = [];
            foreach ($data as $item) {
                if (!empty($item['PlatformAuthRule'])) {
                    $list[] = $item;
                }
            }
            return success($list);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 更新用户信息
     * @return bool|string
     */
    public function updateUserInfo(): bool|string
    {
        try {
            $quick_entrance = $this->request->param('quick_entrance');
            $UserModel = new UserModel();
            $info = $UserModel->find($this->userData['id']);
            if (!$info) throw new \Exception('参数错误！');
            $info->quick_entrance = $quick_entrance;
            $info->save();
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 是否红点消息
     * @return bool|string
     */
    public function dotRemind(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            if (!empty($param['channel'])){
                $where[] = ['channel', '=', $param['channel']];
            }
            $where[] = ['uid', '=', $this->userData['id']];
            $where[] = ['is_see', '=', 0];
            $MessageModel = new MessageModel();
            $is_dot = $MessageModel->where($where)->value('id');
            return success([
                'is_dot' => $is_dot?1:0
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 消息提醒
     * @return bool|string
     */
    public function remind(): bool|string
    {
        try {
            switch ($this->userData['type']) {
                case 0:
                    throw new \Exception('开发人员没有消息提醒');
                case 1:
                    //公司
                    $CompanyConfigModel = new CompanyConfigModel();
                    $config = $CompanyConfigModel->where([
                        ['company_id', '=', $this->userData['company_id']],
                        ['key', '=', 'software_settings']
                    ])->value('value');
                    break;
                case 2:
                    //平台
                    $PlatformConfigModel = new PlatformConfigModel();
                    $config = $PlatformConfigModel->where([
                        ['platform_id', '=', $this->userData['platform_id']],
                        ['key', '=', 'software_settings']
                    ])->value('value');
                    break;
                case 3:
                case 4:
                    //单位-部门
                    $ConfigModel = new ConfigModel();
                    $config = $ConfigModel->where([
                        ['unit_id', '=', $this->userData['unit_id']],
                        ['key', '=', 'soft_setting']
                    ])->value('value');
                    break;
            }
            if (empty($config)) throw new \Exception('未开启消息中心！');
            $config = json_decode($config, true);
            if ($config['news_center'] != 1) throw new \Exception('未开启消息中心！');
            $param = $this->request->param();
            $this->validate($param,[
                'pageSize|每页显示数量' => 'require'
            ]);
            $where = [];
            if (!empty($param['channel'])){
                $where[] = ['channel', '=', $param['channel']];
            }
            $where[] = ['uid', '=', $this->userData['id']];
            $config['news_type'] = $config['news_type'] ?? [];
            if (!empty($config['news_type'])) {
                $type = [];
                foreach ($config['news_type'] as $item) {
                    switch ($item) {
                        case 1:
                            //测评任务消息
                            $type[] = 3;
                            $type[] = 4;
                            $type[] = 5;
                            $type[] = 7;
                            $type[] = 8;
                            $type[] = 9;
                            $type[] = 10;
                            break;
                        case 2:
                            //预警报告消息
                            $type[] = 6;
                            $type[] = 11;
                            break;
                        case 3:
                            //预约咨询消息
                            $type[] = 17;
                            $type[] = 18;
                            break;
                        case 4:
                            //系统通知/公告
                            $type[] = 1;
                            $type[] = 2;
                            $type[] = 23;
                            break;
                        case 5:
                            //危机干预
                            $type[] = 14;
                            $type[] = 15;
                            $type[] = 16;
                            break;
                        case 6:
                            //物联网消息
                            $type[] = 22;
                            break;
                    }
                }
                if (!empty($type)) {
                    $where[] = ['type', 'in', $type];
                } else {
                    $where[] = ['id', '=', -1];
                }
            } else {
                $where[] = ['id', '=', -1];
            }
            $MessageModel = new MessageModel();
            $data = $MessageModel->where($where)->order('id','desc')->paginate($param['pageSize'])->toArray();
            foreach ($data['data'] as &$item) {
                $item['img'] = '/icon_task/202411/07_1730960430672c5c2ee2c98.png';
                if ($item['is_see'] == 0){
                    $dot[] = $item['id'];
                }
            }
            if (!empty($dot)){
                $MessageModel->where('id','in',$dot)->update(['is_see' => 1]);
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 消息提醒-清空
     * @return bool|string
     */
    public function remindClear(): bool|string
    {
        try {
            $MessageModel = new MessageModel();
            $MessageModel->where('uid', '=', $this->userData['id'])->update([
                'is_del' => 1,
                'del_time' => time()
            ]);
            return success([], '清空成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 消息提醒-删除
     * @return bool|string
     */
    public function remindDel(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $MessageModel = new MessageModel();
            $info = $MessageModel->find($id);
            if (!$info) throw new \Exception('参数错误！');
            $info->is_del = 1;
            $info->del_time = time();
            $info->save();
            return success([], '删除成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    public function getNewsTypeImg($type): string
    {
        return match ($type) {
            3, 4, 5, 7, 8, 9, 10 => '/icon_task/202411/07_1730960087672c5ad715646.png',//测评任务消息
            6, 11, 1, 2, 14, 15, 16, 23 => '/icon_task/202411/07_1730960430672c5c2ee2c98.png',//预警报告消息-系统通知-公告-危机干预
            17 => '/icon_task/202411/07_1730944047672c1c2fd624c.png',//预约咨询消息
            22 => '/icon_task/202411/07_1730941588672c1294c2e1e.png',//物联网消息
        };
    }

    /**
     * 消息
     * @return bool|string
     */
    public function message(): bool|string
    {
        try {
            $where = [];
            $where[] = ['uid', '=', $this->userData['id']];
            $MessageModel = new MessageModel();
            $data = $MessageModel->where($where)->order('id desc')->limit(0, 4)->select()->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

}